package com.acme;

import java.util.ArrayList;
import java.util.Iterator;

import android.app.ListActivity;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.inputmethod.InputMethodManager;
import android.widget.Button;
import android.widget.ListView;
import android.widget.TextView;

public class AwardWinners extends ListActivity {

	ArrayList<AwardWinner> results;
	TextView searchText;
	String searchTerm = null;

	private AwardWinnersResponseReceiver receiver;
	
	public class AwardWinnersResponseReceiver extends BroadcastReceiver {
		   public static final String ACTION_RESP = "com.test.intent.action.AWARD_WINNERS_RECV";
		 
		   @Override
		    public void onReceive(Context context, Intent intent) {
		       	String response = intent.getStringExtra(FootballStatsService.GET_WINNERS_OUT_JSON);
		       	results = AwardWinner.getAwardWinners(response);
		       	
				setListAdapter(
					new AwardWinnerListAdapter(
						AwardWinners.this.getApplicationContext(),
						R.layout.winner_list_item, 
						results.toArray(new AwardWinner[results.size()])
					)
				);
		    }
	}
	
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.award_winners);
		
		Intent intent = getIntent();
		String award = intent.getStringExtra(AwardWinner.AWARD_NAME);
		
		IntentFilter filter = new IntentFilter(AwardWinnersResponseReceiver.ACTION_RESP);
		filter.addCategory(Intent.CATEGORY_DEFAULT);
		receiver = new AwardWinnersResponseReceiver();
		registerReceiver(receiver, filter);

		Intent msgIntent = new Intent(this, FootballStatsService.class);
		msgIntent.putExtra(FootballStatsService.ACTION,FootballStatsService.ACTION_GET_WINNERS);
		msgIntent.putExtra(FootballStatsService.GET_WINNERS_IN_TITLE, award);
		startService(msgIntent);
	}

	public void onListItemClick(ListView parent, View view, int position,long id) {
		AwardWinner selected = (AwardWinner) this.getListAdapter().getItem(position);
		Intent newIntent = new Intent(this, PlayerProfile.class);
		newIntent.putExtra(Player.PLAYER_ID, selected.id);
		startActivity(newIntent);
	}

	public void onDestroy(){
		super.onDestroy();
		unregisterReceiver(receiver);
	}
}
